<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Service</title>
        <script src="http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script>
        <script src="http://apps.bdimg.com/libs/angular.js/1.5.0-beta.0/angular-route.js" charset="utf-8"></script>
        <link href="http://libs.baidu.com/bootstrap/3.0.3/css/bootstrap.min.css" rel="stylesheet">    
    </head>
    <body>
        <h2>AngularJS Sample Application</h2>
        <div ng-app="mainApp" ng-controller="CalcController">
            <p>
                Enter a number： <input type="number" ng-model="number" />
                <button ng-click="square()">X<sup>2</sup></button>
            </p>
            
            <p>
                Result: {{ result }}
            </p>
        </div>
        <script>
            var mainApp = angular.module('mainApp', []);
            mainApp.factory('MathService', function() {
                var factory = {};
                factory.multiply = function(a, b) {
                    return a * b;
                } 
                return factory;
            });
            
            mainApp.service('CalcService', function(MathService) {
                this.square = function(a) {
                    return MathService.multiply(a, a);
                }
            });
            
            // mainApp.controller('CalcController', function($scope, CalcService) {
            //    $scope.square = function() {
            //        $scope.result = CalcService.square($scope.number);
            //    }
            // });
            
            mainApp.controller('CalcController', function($scope, MathService) {
                $scope.square = function() {
                    $scope.result = MathService.multiply($scope.number, $scope.number);
                } 
            });
        </script>
    </body>
</html>